<template>
    <!-- 模板部分保持不变 -->
    <div class="icon-updater" @click="handleClick">
        <n-icon :size="16" color="#fff">
            <Build />
        </n-icon>
    </div>
    <n-modal v-model:show="showModal" :close-on-esc="false" :mask-closable="false">
        <n-card style="width: 400px" title="软件更新中" :bordered="false" size="huge" role="dialog" aria-modal="true">
            <div class="updataer__warning--text">
                <n-icon size="16" color="#FFA500">
                    <WarningOutline></WarningOutline>
                </n-icon>
                <p>软件更新中，请勿退出！</p>
            </div>
            <n-progress :color="{ stops: ['#E3F2FD', '#2080f0'] }" type="line" :percentage="processingComputed"
                indicator-placement="inside" processing />
        </n-card>
    </n-modal>
</template>

<script setup lang='ts'>
import { check } from '@tauri-apps/plugin-updater';
import { relaunch } from '@tauri-apps/plugin-process';
import { useMessage } from 'naive-ui';
import { WarningOutline, Build } from '@vicons/ionicons5';
import { useAppStore } from '@/stores/app';

const loading = ref(false);
const appStore = useAppStore();
const showModal = ref(false);
const donwloadNumber = ref(0);
const totalLoadNumber = ref(0);
const message = useMessage();
const processingComputed = computed(() => {
    if (totalLoadNumber.value === 0) return 0;
    return Math.floor(donwloadNumber.value * 100 / totalLoadNumber.value);
})

// 更新
const handleClick = async () => {
    try {
        if (loading.value) return;
        loading.value = true;

        // 检查更新
        const update = await check();
        if (!update) throw new Error('update为null');
        showModal.value = true;
        let downloaded = 0;
        let contentLength = 0;

        // 检查update对象是否包含必要字段
        if (!update.version || !update.date || !update.body) throw new Error('更新信息不完整！');

        // 下载并安装更新
        await update.downloadAndInstall((event) => {
            switch (event.event) {
                case 'Started':
                    contentLength = event.data.contentLength || 0;
                    totalLoadNumber.value = contentLength;
                    break;
                case 'Progress':
                    downloaded += event.data.chunkLength;
                    donwloadNumber.value = downloaded;
                    break;
                case 'Finished':
                    console.log('下载完成');
                    break;
            }
        });

        message.success('更新完成，即将重启应用！');
        await relaunch();
    } catch (error: any) {
        showModal.value = false;
        console.error('更新错误:', error);

        if (error.message?.includes('Could not fetch a valid release JSON') ||
            error.message?.includes('已经是最新版本')) {
            message.warning(`v${appStore.version}已经是最新版本`);
        } else {
            message.error(`更新出错：${error?.message || error || '未知错误'}`);
        }
    } finally {
        loading.value = false;
    }
}
</script>
<style scoped lang='scss'>
.icon-updater {
    height: 25px;
    width: 25px;
    display: flex;
    justify-content: center;
    align-items: center;

    i {
        transition: 0.27s all;
    }

    &:hover i {
        transform: rotate(-25deg);
    }
}

.updataer__warning--text {
    display: flex;
    align-items: center;
    margin-bottom: 1rem;
    color: #FFA500;
    gap: 12px;
}
</style>